﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using System.IO;
using HSJM.Service.MWS.Core;
using HSJM.Service.MWS.Infrastructure;
using HSJM.Service.MWS.Domain;
using HSJM.Service.MWS.Application;
using HSJM.Service.MWS.Domain.Domain.Base;
using HSJM.Service.MWS.Application.Application.Base;
using HSJM.Service.MWS.Domain.Domain;
using HSJM.Service.MWS.Application.Application;
using HSJM.Service.MWS.Utility;

namespace HSJM.Service.MWS.AutoInject
{
    /// <summary>
    /// 注入服务
    /// </summary>
    public static class RegisterService
    {
        /// <summary>
        /// 自动注入
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static void RegisterComponents(this IServiceCollection services)
        {
            services.AddScoped<RedisHelper>();

            RegisterDomain.RegisterComponents(services);
            RegisterInfrastructure.RegisterComponents(services);
            RegisterApplication.RegisterComponents(services);

            var allTypes = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll")
                    .Where(p => !Path.GetFileName(p).StartsWith("System.")
                                && !Path.GetFileName(p).StartsWith("Microsoft."))
                    .Select(Assembly.LoadFrom)
                    .SelectMany(y => y.DefinedTypes)
                    .ToList();
            allTypes?.ForEach(thisType =>
            {
                //注入的限制
                var allInterfaces = thisType.GetInterfaces().Where(p => p.GetInterfaces().Contains(typeof(IBaseApplication<,>)) || p.GetInterfaces().Contains(typeof(IBaseDomain<,>))).ToList();
                allInterfaces?.ForEach(thisInterface => {
                    services.AddScoped(thisInterface, thisType);//只要符合条件的所有接口都注入t类
                });
            });
        }

        /// <summary>
        /// 自动创建映射
        /// </summary>
        /// <param name="services"></param>
        public static void AddAutoMapper(this IServiceCollection services)
        {
            var allProfile = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll")
                .Where(p => !Path.GetFileName(p).StartsWith("System.")
                            && !Path.GetFileName(p).StartsWith("Microsoft."))
                .Select(Assembly.LoadFrom)
                .SelectMany(y => y.DefinedTypes)
                .Where(x => typeof(Profile).IsAssignableFrom(x) && x.IsClass)?
                .ToArray();
            if (allProfile != null)
                services.AddAutoMapper(allProfile);
        }
    }
}
